<?php

namespace Finley\BlogBundle\Controller;

use Finley\BlogBundle\Entity\Setting;
use Finley\BlogBundle\Repository\SettingRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{

    public function __construct()
    {
    }

    public function indexAction()
    {
        // Bundle:folder:file
        // bug 不要用 $this->render('FinleyBlogBundle:Default:index.html.twig');
        // https://symfony.com/doc/3.4/templating.html#referencing-templates-in-a-bundle
        // @FinleyBlogBundle -> FinleyBlog

        // Respository是一个PHP类，它的唯一工作就是帮助你从那个特定的类中取出entity
        $repository = $this->getDoctrine()->getRepository('FinleyBlogBundle:Setting');
        $settings = $repository->findAllOrderSetting();

        // $settings = $repository->findAll();

        print_r($settings);


        print_r($settings);

        return $this->render('@FinleyBlog/Default/index.html.twig');
    }

    public function createAction()
    {
        $entityManager = $this->getDoctrine()->getManager();

        $setting = new Setting();
        $setting->setField('slogan')->setData('hello world');

        // 这个不是真正的执行，到底有啥用，目的是啥, 优化性能？
        $entityManager->persist($setting);

        $entityManager->flush();

        return new Response('Saved new product with id ' . $setting->getId());
    }

    public function showAction(Request $request)
    {
        $id = $request->get('id');

        $setting = $this->getDoctrine()->getRepository(Setting::class)->find($id);

        if (!$setting) {
            throw $this->createNotFoundException(
                'No setting found for id '. $id
            );
        }

        return new Response($setting->getField());
    }

    public function find($id)
    {
        $setting = $this->getDoctrine()->getRepository(Setting::class)->find($id);

        if (!$setting) {
            throw $this->createNotFoundException(
                'No setting found for id '. $id
            );
        }

        return $setting;
    }

    public function updateAction(Request $request)
    {
        $entityManager = $this->getDoctrine()->getManager();

        $id = $request->get('id');

        $setting = $this->find($id)->setData('xxx');

        $entityManager->flush();

        return new Response($setting->getField());
    }

    public function deleteAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $id = $request->get('id');

        $setting = $this->find($id);

        $em->remove($setting);

        $em->flush();

        return $this->indexAction();
    }
}
